package com.lzy.websocket.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.StringTokenizer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.lzy.websocket.bean.Message;
import com.lzy.websocket.service.MessageService;

/**
 * 请求处理器类
 * @author lzy
 *
 */
public class WebSocketHander implements WebSocketHandler {

	private static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();
    
    @Autowired
	private MessageService messageService;
    
    /**
     * 连接建立后执行的操作
     */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		users.add(session);
	}

	/**
	 * 收到消息后执行的操作
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		String content = (String)message.getPayload();
		StringTokenizer st = new StringTokenizer(content,";");
		String receiver = st.nextToken();
		content = st.nextToken();
		/* 将消息写入数据库 */
		Message mes = new Message();
		mes.setSendTime(new Date());
		mes.setContent(content);
		mes.setNew(true);
		mes.setSender((String) session.getAttributes().get("WEBSOCKET_USERNAME"));
		mes.setReceiver(receiver);
		messageService.insertMessage(mes);
		/* 若消息接收者也在线，将消息推送之 */
		for (WebSocketSession user : users) {
			if (user.getAttributes().get("WEBSOCKET_USERNAME").equals(receiver)) {
				try {
                    if (user.isOpen()) {
                        user.sendMessage(new TextMessage(content));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
			}
		}
	}

	/**
	 * 发生错误时执行的操作
	 */
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if (session.isOpen()) {
			session.close();
        }
		users.remove(session);
	}

	/**
	 * 连接结束后执行的操作
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		users.remove(session);
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}

}
